import { inject, onBeforeMount, ref } from 'vue'
import { usePassword } from './usePassword'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { useUserInfoStore } from '@/stores/modules/userInfo'
import { apiGetInviteInfo, apiInviteLogin, apiJoinTeam } from '@/api/user'
import type { InviteLogin, InviteInfo } from '@/api/type'
import { AGREEMENT_TYPE } from '@/const'

interface Options<T = any> {
  callback?: () => void
}
export const useInvite = (options: Options) => {
  const route = useRoute()
  const inviteInfoId = ref<string>('')
  let inviteInfo = ref<InviteInfo>({
    customerId: '',
    id: '',
    phone: '',
    teamId: '',
    teamName: ''
  })
  const customerId = ref<string>('')
  const userStore = useUserInfoStore()
  onBeforeMount(async () => {
    inviteInfoId.value = route?.params.id as string
    if (userStore.frontToken) {
      isLogin.value = await userStore.checkToken()
    } else {
      isLogin.value = false
    }
    await getInviteInfo()
  })

  const isLogin = ref<boolean>(false)
  const router = useRouter()
  const inviteLogin = async () => {
    try {
      const {
        data: { entity }
      } = await apiInviteLogin(formState)
      console.log('entity', entity)
      customerId.value = entity
      message.success('登录成功')
    } catch (error: any) {
      console.log('error', error)
    }
  }
  const getInviteInfo = async () => {
    const {
      data: { entity }
    } = await apiGetInviteInfo({ inviteInfoId: inviteInfoId.value })
    console.log('entity', entity)
    inviteInfo.value = entity
    console.log('entity', entity, inviteInfo.value)
  }
  const setIntervalValue= inject('setIntervalValue', () => {})
  const JoinTeam = async () => {
    const {
      data: { entity }
    } = await apiJoinTeam({ customerId: customerId.value, inviteInfoId: inviteInfoId.value })
    console.log('entity', entity)
    message.success('加入成功')
    if (options?.callback) {
      options.callback?.()
      return
    }
    userStore.setFrontToken(entity)
    await userStore.setUserInfo()
    setIntervalValue()
    router.replace({ name: 'chatDefault' })
  }
  const { formState, codeState, phoneValidate, getCode } = usePassword({})

  const isAgree = ref<boolean>(false)
  const getIsChecked = () => {
    if (!isAgree.value) return message.error('请先同意用户协议')
    inviteLogin()
  }

  const agreementVisible = ref(false)
  const agreementType = ref<AGREEMENT_TYPE>(AGREEMENT_TYPE.用户协议)
  const openAgreement = (type: AGREEMENT_TYPE) => {
    agreementType.value = type
    agreementVisible.value = true
  }

  return {
    formState,
    codeState,
    phoneValidate,
    getCode,
    inviteLogin,
    JoinTeam,
    isLogin,
    customerId,
    inviteInfo,
    isAgree,
    getIsChecked,
    openAgreement,
    agreementType,
    agreementVisible
  }
}
